const AWS = require("aws-sdk");
const dotenv = require("dotenv");
dotenv.config({ path: "../config.env" });

const STS = new AWS.STS({
  accessKeyId: process.env.AWS_ACCESS_KEY,
  secretAccessKey: process.env.AWS_SECRET_KEY,
  region: "cn-northwest-1",
});

const consultBucketPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "VisualEditor0",
      Effect: "Allow",
      Action: ["s3:PutObject", "s3:DeleteObject"],
      Resource: "arn:aws-cn:s3:::consult/*",
    },
  ],
};

//the user can assune the consultRole and this role has the permission of s3 full access
const params = {
  DurationSeconds: 3600,
  Policy: JSON.stringify(consultBucketPolicy), //Resultant policy is the intersetion of AmazonS3FullAccess and consultBucketPolicy
  RoleArn: "arn:aws-cn:iam::796401082536:role/consultRole",
  RoleSessionName: "consultRole",
};

const assumeRole = () => {
  return new Promise((resolve, reject) => {
    STS.assumeRole(params, (err, data) => {
      if (err) reject(console.log("-----", err));
      else resolve(data.Credentials);
    });
  });
};

const getCredential = async (req, res) => {
  try {
    //获取凭证
    console.log("开始获取凭证");
    const Credentials = await assumeRole();
    console.log("获取aws凭证成功");
    res.status(200).json({
      status: "success",
      credential: { ...Credentials },
    });
  } catch (err) {
    console.log("获取aws凭证失败", err);
  }
};

module.exports = { getCredential };
